var express = require('express');
var router = express.Router();
var ws = require("nodejs-websocket");
var SQL = require("../../utils/mysql");

var mySQL;
const { id_name } = require("./data.js");

var startFlag = false;
var timerAlive = false;
// var quesList = ['60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80'];
var quesList = [];
// 渲染piano.ejs
router.get('/', function (req, res, next) {
    res.render('piano', { title: 'Piano', message: '按下键盘, 渲染五线谱.' });
});

console.log("开始建立连接...")
var server = ws.createServer(function (conn) {

    conn.on("text", main);// 当接收到前端的数据时
    conn.on("close", function (code, reason) {
        console.log("关闭连接")
    });
    conn.on("error", function (code, reason) {
        console.log("异常关闭")
    });
}).listen(8001)
console.log("WebSocket建立完毕")


router.post('/midi', function (req, res, next) {
    if (startFlag) {
        const kids = req.body.key.sort((a, b) => a - b);
        check(kids); // 检查结果是否正确
        sendNotes('ans', kids);
        res.send('ok');
    } else {
        res.send('please press START');
    }
});

function main(text) {
    if (startFlag) {
        if (text === 'end') {
            startFlag = false;
            timerAlive = false;
            quesList = [];
            mySQL.clearAllSelected();
            return;
        }
        timerAlive = false;
        process_quesList(text);
        setTimeout(function () {
            if (startFlag) {
                const kids = quesList[0].ques.split('_');
                sendNotes('que', kids);
                timerAlive = true;
            }
        }, 1000);
    } else if (text === 'start') {
        mySQL = new SQL();
        startFlag = true;
        timerAlive = true;
        quesList_addN(20).then(() => {
            const kids = quesList[0].ques.split('_');
            sendNotes('que', kids);
        })
    }
}

// 处理问题列表的核心算法
function process_quesList(time) {
    var tmp;
    if (time < 30) {
        tmp = quesList.shift();
        tmp.count++;
        // 数据库次数+1
        mySQL.exec({
            sql: `UPDATE wzm SET count = ${tmp.count} where id = ${tmp.id}`,
        });
        if (tmp.count < 2) {
            quesList.push(tmp);
        } else {
            mySQL.exec({
                sql: `UPDATE wzm SET isSelected = 0 ,isToday = 0 where id = ${tmp.id}`,
            });
        }
    } else if (time < 40) {
        tmp = quesList.shift();
        quesList.splice(-3, 0, tmp);
    } else {
        tmp = quesList.shift();
        // 数据库次数归0
        if (tmp.count !== 0) {
            tmp.count = 0;
            mySQL.exec({
                sql: `UPDATE wzm SET count = ${tmp.count} where id = ${tmp.id}`,
            });
        }
        quesList.splice(2, 0, tmp);
    }
    if (quesList.length < 20) {
        // 从数据库补充问题
        const n = 20 - quesList.length;
        quesList_addN(n);
    }
    console.log("quesList长度:", quesList.length)
}

// 检查输入的kids是否正确
function check(kids) {
    if (timerAlive) {
        const kids_str = kids.join('_');
        if (kids_str === quesList[0].ques) {
            server.connections.forEach(function (conn) {
                conn.sendText('correct')
            })
        }
    }
}

// 向前端发送音符
function sendNotes(type, kids) {
    var nids_str = ''
    var index = 0;
    id_name.forEach(item => {
        if (index < kids.length && item.id === Number(kids[index])) {
            nids_str = nids_str + '_' + item.name;
            index++;
        }
    })
    const clef = quesList[0].clef ? 'treble' : 'bass';
    const keySignature = quesList[0].keySignature;
    const header = `${type}_${clef}_${keySignature}`;
    server.connections.forEach(function (conn) {
        conn.sendText(header + nids_str);
    })
}

// 为quesList从数据库抓取数据
async function quesList_addN(n) {
    var ids = [];
    let extra = '';
    extra = 'and clef = 1';
    const result = await mySQL.execPromise({
        sql: `select * from wzm where isToday = 1 and isSelected = 0 and count < 4 ${extra} order by rand() Limit ${n}`
    });
    if (result.length !== n) {
        console.log('！！！数据库未清理！！！')
    }
    quesList.push(...result);
    console.log("quesList:", quesList.length)
    result.forEach(data => {
        ids.push(data.id);
    });
    mySQL.markSelected(ids);
}

module.exports = router;
